<template>
  <div class="profile-page" v-loading="loading" element-loading-text="加载中...">
    <el-row :gutter="20">
      <!-- 左侧: 个人信息预览 -->
      <el-col :xs="24" :lg="8">
        <el-card shadow="never" class="profile-preview">
          <div class="avatar-wrapper">
            <div class="avatar-container">
              <el-avatar :size="96" :src="userInfo.avatar"></el-avatar>
              <el-upload
                :show-file-list="false"
                :before-upload="handleAvatarUpload"
                :http-request="handleCustomUpload"
              >
                <el-button 
                  icon="el-icon-camera" 
                  circle 
                  size="small"
                  class="avatar-upload-btn"
                ></el-button>
              </el-upload>
            </div>
            <h2 class="user-name">{{ userInfo.name }}</h2>
            <!-- <p class="user-desc">{{ userInfo.major }} - {{ userInfo.grade }}</p> -->
          </div>

          <div class="info-list">
            <div class="info-item">
              <div class="info-icon">
                <i class="el-icon-user"></i>
              </div>
              <div class="info-content">
                <p class="info-label">账号</p>
                <p class="info-value">{{ userInfo.username }}</p>
              </div>
            </div>

            <div class="info-item">
              <div class="info-icon">
                <i class="el-icon-phone"></i>
              </div>
              <div class="info-content">
                <p class="info-label">联系电话</p>
                <p class="info-value">{{ maskPhone(userInfo.phone) }}</p>
              </div>
            </div>

            <div class="info-item">
              <div class="info-icon">
                <i class="el-icon-postcard"></i>
              </div>
              <div class="info-content">
                <p class="info-label">证件号码</p>
                <p class="info-value">{{ maskIdCard(userInfo.idCard) }}</p>
              </div>
            </div>

            <div class="info-item">
              <div class="info-icon">
                <i class="el-icon-date"></i>
              </div>
              <div class="info-content">
                <p class="info-label">注册时间</p>
                <p class="info-value">{{ userInfo.registerDate }}</p>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧: 编辑信息表单 -->
      <el-col :xs="24" :lg="16">
        <!-- 基本信息 -->
        <el-card shadow="never" class="form-card">
          <div slot="header" class="card-header">
            <h3 class="card-title">基本信息</h3>
          </div>

          <el-form 
            :model="basicForm" 
            :rules="basicRules" 
            ref="basicForm"
            label-width="100px"
            class="basic-form"
          >
            <el-row :gutter="20">
              <el-col :xs="24" :md="12">
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="basicForm.name"></el-input>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :md="12">
                <el-form-item label="联系电话" prop="phone">
                  <el-input v-model="basicForm.phone"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="证件号码" prop="idCard">
              <el-input v-model="basicForm.idCard" style="max-width: 500px;"></el-input>
            </el-form-item>

            <el-divider content-position="left">
              <i class="el-icon-lock"></i> 修改密码（选填）
            </el-divider>

            <el-row :gutter="20">
              <el-col :xs="24" :md="12">
                <el-form-item label="旧密码" prop="oldPassword">
                  <el-input 
                    v-model="basicForm.oldPassword" 
                    type="password"
                    placeholder="不修改密码请留空"
                    show-password
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :md="12">
                <el-form-item label="新密码" prop="newPassword">
                  <el-input 
                    v-model="basicForm.newPassword" 
                    type="password"
                    placeholder="不修改密码请留空"
                    show-password
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :xs="24" :md="12">
                <el-form-item label="确认新密码" prop="confirmPassword">
                  <el-input 
                    v-model="basicForm.confirmPassword" 
                    type="password"
                    placeholder="不修改密码请留空"
                    show-password
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <p class="password-hint" v-if="basicForm.newPassword">
              <i class="el-icon-info"></i> 密码长度至少6位，包含字母和数字
            </p>

            <el-form-item>
              <el-button 
                type="primary" 
                @click="handleBasicSave" 
                :loading="saving"
              >
                <i class="el-icon-check"></i> 保存修改
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { formatDate, getAvatarUrl } from '@/utils/url'

export default {
  name: 'Profile',
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号'))
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }

    const validateIdCard = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入证件号码'))
      } else if (!/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/.test(value)) {
        callback(new Error('请输入正确的身份证号码'))
      } else {
        callback()
      }
    }

    const validateNewPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入新密码'))
      } else if (value.length < 6) {
        callback(new Error('密码长度至少6位'))
      } else if (!/(?=.*[a-zA-Z])(?=.*\d)/.test(value)) {
        callback(new Error('密码必须包含字母和数字'))
      } else {
        callback()
      }
    }

    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    return {
      saving: false,
      loading: false,
      userInfo: {
        avatar: '',
        name: '',
        username: '',
        phone: '',
        idCard: '',
        major: '',
        grade: '',
        registerDate: ''
      },
      basicForm: {
        name: '',
        studentId: '',
        phone: '',
        idCard: '',
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      basicRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        idCard: [
          { required: true, validator: validateIdCard, trigger: 'blur' }
        ],
        oldPassword: [
          { validator: (rule, value, callback) => {
            // 如果填写了新密码，则旧密码必填
            if (this.basicForm.newPassword && !value) {
              callback(new Error('修改密码时必须输入旧密码'))
            } else {
              callback()
            }
          }, trigger: 'blur' }
        ],
        newPassword: [
          { validator: (rule, value, callback) => {
            // 如果填写了新密码，需要验证格式
            if (value) {
              if (value.length < 6) {
                callback(new Error('密码长度至少6位'))
              } else if (!/(?=.*[a-zA-Z])(?=.*\d)/.test(value)) {
                callback(new Error('密码必须包含字母和数字'))
              } else {
                callback()
              }
            } else {
              callback()
            }
          }, trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: (rule, value, callback) => {
            // 如果填写了新密码，则确认密码必须一致
            if (this.basicForm.newPassword && value !== this.basicForm.newPassword) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          }, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getProfile()
  },
  methods: {
    // 处理头像URL：将相对路径转换为完整URL，添加时间戳防止缓存
    processAvatarUrl(avatar) {
      if (!avatar || avatar === '') {
        return 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
      }
      
      // Base64格式，直接返回
      if (avatar.startsWith('data:image/')) {
        return avatar
      }
      
      // 已经是完整URL，添加时间戳后返回
      if (avatar.startsWith('http://') || avatar.startsWith('https://')) {
        const timestamp = Date.now()
        return avatar + (avatar.includes('?') ? '&' : '?') + '_t=' + timestamp
      }
      
      // 相对路径，使用 getAvatarUrl 转换为完整URL，然后添加时间戳
      const fullUrl = getAvatarUrl(avatar)
      if (fullUrl && fullUrl !== 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png') {
        const timestamp = Date.now()
        return fullUrl + (fullUrl.includes('?') ? '&' : '?') + '_t=' + timestamp
      }
      
      return fullUrl
    },
    
    // 获取用户资料
    async getProfile() {
      try {
        this.loading = true
        // 从 home 接口的 user_info 获取 (后端返回: {id, name, username, phone, avatar})
        const res = await this.$api.profile.getProfile()
        
        // 映射后端数据到前端
        this.userInfo = {
          avatar: this.processAvatarUrl(res.avatar || ''),
          name: res.name || '',
          username: res.username || '',
          phone: res.phone || '',
          idCard: res.id_card || '',
          major: '-', // 后端 user_info 不返回专业
          grade: '-', // 后端 user_info 不返回年级
          registerDate: res.created_at ? formatDate(res.created_at) : '-' // 格式化为 Y-m-d
        }
        
        // 同步到编辑表单
        this.basicForm = {
          name: res.name || '',
          studentId: res.id || '',
          phone: res.phone || '',
          idCard: res.id_card || '',
          oldPassword: '',
          newPassword: '',
          confirmPassword: ''
        }
        
      } catch (error) {
        this.$message.error('获取用户资料失败')
      } finally {
        this.loading = false
      }
    },
    maskPhone(phone) {
      if (!phone) return ''
      return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
    },
    maskIdCard(idCard) {
      if (!idCard) return ''
      return idCard.replace(/(\d{3})\d{8}(\d{4})/, '$1********$2')
    },
    // 自定义上传处理，阻止默认上传行为
    handleCustomUpload() {
      // 空函数，阻止 el-upload 的默认上传行为
      // 实际的上传逻辑在 handleAvatarUpload 中处理
    },
    async handleAvatarUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
        return false
      }

      try {
        // 转为 base64 用于预览
        const reader = new FileReader()
        reader.onload = async (e) => {
          // 更新头像(实际应该上传到服务器获取URL,这里简化处理)
          const base64Avatar = e.target.result
          
          try {
            const res = await this.$api.profile.updateProfile({
              avatar: base64Avatar
            })
            
            // 获取返回的头像URL（可能是base64或服务器URL）
            const rawAvatarUrl = res?.data?.avatar || res?.avatar || base64Avatar
            
            // 使用 processAvatarUrl 处理头像URL，确保格式正确（添加时间戳、处理相对路径等）
            const processedAvatarUrl = this.processAvatarUrl(rawAvatarUrl)
            
            // 更新本地用户信息（使用Vue.set确保响应式）
            this.$set(this.userInfo, 'avatar', processedAvatarUrl)
            
            // 更新localStorage中的用户信息（保存原始URL，不带时间戳）
            const savedUserInfo = localStorage.getItem('userInfo')
            if (savedUserInfo) {
              try {
                const userInfo = JSON.parse(savedUserInfo)
                // 保存原始头像URL（不带时间戳），让Layout组件处理URL转换
                const updatedUserInfo = {
                  ...userInfo,
                  avatar: rawAvatarUrl
                }
                localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))
              } catch (e) {
              }
            } else {
              // 如果localStorage中没有用户信息，创建一个新的
              try {
                const currentUserInfo = await this.$api.profile.getProfile()
                localStorage.setItem('userInfo', JSON.stringify({
                  name: currentUserInfo.name || '',
                  username: currentUserInfo.username || '',
                  phone: currentUserInfo.phone || '',
                  avatar: rawAvatarUrl, // 保存原始URL
                  id_card: currentUserInfo.id_card || ''
                }))
              } catch (e) {
              }
            }
            
            // 触发全局事件通知Layout组件更新头像
            window.dispatchEvent(new CustomEvent('userInfoUpdated'))
            
            this.$message.success('头像上传成功')
          } catch (error) {
            this.$message.error('头像上传失败')
          }
        }
        reader.readAsDataURL(file)
      } catch (error) {
        this.$message.error('头像处理失败')
      }
      
      return false
    },
    async handleBasicSave() {
      this.$refs.basicForm.validate(async (valid) => {
        if (valid) {
          try {
            this.saving = true
            
            const updateData = {
              name: this.basicForm.name,
              phone: this.basicForm.phone,
              id_card: this.basicForm.idCard
            }
            
            // 如果填写了密码相关字段，添加到更新数据中
            if (this.basicForm.newPassword) {
              updateData.old_password = this.basicForm.oldPassword
              updateData.password = this.basicForm.newPassword
              updateData.password_confirmation = this.basicForm.confirmPassword
            }
            
            // 调用更新接口
            await this.$api.profile.updateProfile(updateData)
            
            // 更新本地数据
            this.userInfo.name = this.basicForm.name
            this.userInfo.phone = this.basicForm.phone
            this.userInfo.idCard = this.basicForm.idCard
            
            // 如果修改了密码，提示重新登录
            if (this.basicForm.newPassword) {
              this.$message.success('保存成功，密码已修改，请重新登录')
              setTimeout(() => {
                localStorage.removeItem('student_token')
                localStorage.removeItem('userInfo')
                this.$router.push('/login')
              }, 1500)
            } else {
              this.$message.success('保存成功')
              // 清空密码字段
              this.basicForm.oldPassword = ''
              this.basicForm.newPassword = ''
              this.basicForm.confirmPassword = ''
            }
            
          } catch (error) {
            this.$message.error('保存失败')
          } finally {
            this.saving = false
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.profile-page {
  padding: 20px 0;
}

.profile-preview {
  position: sticky;
  top: 80px;
}

.avatar-wrapper {
  text-align: center;
  margin-bottom: 24px;
}

.avatar-container {
  position: relative;
  display: inline-block;
  margin-bottom: 16px;
}

.avatar-upload-btn {
  position: absolute;
  bottom: 0;
  right: 0;
  background-color: #165DFF;
  color: white;
  border: 2px solid white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.avatar-upload-btn:hover {
  background-color: #4080FF;
  border-color: white;
  color: white;
}

.user-name {
  font-size: 20px;
  font-weight: bold;
  color: #304156;
  margin: 0 0 8px 0;
}

.user-desc {
  font-size: 13px;
  color: #86909C;
  margin: 0;
}

.info-list {
  margin-top: 24px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #f0f5ff;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  margin-top: 2px;
}

.info-icon i {
  font-size: 16px;
  color: #165DFF;
}

.info-content {
  margin-left: 12px;
  flex: 1;
}

.info-label {
  font-size: 13px;
  color: #86909C;
  margin: 0 0 4px 0;
}

.info-value {
  font-size: 14px;
  color: #304156;
  margin: 0;
}

.form-card {
  margin-bottom: 20px;
}

.form-card:last-child {
  margin-bottom: 0;
}

.card-header {
  margin: 0;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
  color: #304156;
  margin: 0;
}

.basic-form,
.password-form {
  margin-top: 24px;
}

.password-hint {
  font-size: 12px;
  color: #86909C;
  margin: 0 0 20px 0;
  line-height: 1.5;
  padding-left: 100px;
}

.password-hint i {
  margin-right: 4px;
}

@media (max-width: 992px) {
  .profile-preview {
    margin-bottom: 20px;
  }
  
  .form-card {
    margin-top: 20px;
  }
}
</style>
